<script>
import WCompress from '@/components/w-compress/w-compress.vue';
import {
  dataURLtoFile,
  chooseImgs
} from '@/utils/files.js';

// 需要手动在当前页面的 template 内使用挂载 WCompress
export default {
  name: 'ChooseFile',

  components: {
    WCompress
  },

  methods: {
    // 获取压缩后的图片文件
    getFiles() {
      return chooseImgs().then(res => {
        const { files, paths } = res;
        const dealFiles = [];
        return this.picCompress(paths).then(dealRes => {
          dealRes.forEach((b64, index) => {
            dealFiles.push({
              file: dataURLtoFile(b64, files[index].name),
              img: b64
            });
          });
          return Promise.resolve(dealFiles);
        });
      });
    },

    // 压缩
    picCompress(tempFilePaths) {
      return this.$refs.wCompress.start(tempFilePaths);
    }
  },

  render(h) {
    const wCompress = h(WCompress, {
      props: {
        ref: 'wCompress',
        pixels: 500000
      }
    });
    return h('view', [wCompress]);
  }
};
</script>
